﻿// Extensions Made Easy - Copyright 2012 by Jan Van der Haegen - All rights reserved, use for educational purposes only.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.LightSwitch.Runtime.Shell.ViewModels.Commands;

namespace ExtensionsMadeEasy.ClientAPI.Utilities.Base
{
    [InheritedExport(typeof(IShellCommandGroupProvider))]
    public abstract class CodeExecuterHook : IShellCommandGroupProvider
    {
        //TODO: this is a really "late" hook, try to implement this in a way it gets executed way earlier during startup.
        private static readonly IEnumerable<IShellCommandGroup> EmptyList = new List<IShellCommandGroup>();
        private bool executed = false;

        public System.Collections.Generic.IEnumerable<IShellCommandGroup> GetShellCommandGroups(Microsoft.LightSwitch.Client.IScreenObject currentScreen)
        {
            Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(
                () =>
                {
                    if (!this.executed)
                    {
                        try
                        {
                            this.Execute();
                        }
                        finally
                        {
                            this.executed = true;
                        }
                    }
                });
            return EmptyList;
        }

        abstract protected void Execute();
    }
}